/* internal/js/ajax-handler.js */

function getXmlHttpObject () {
	try {
		// Firefox, et al.
		return new XMLHttpRequest();
	} catch (e) {
		// IE
		try {
			return new ActiveXObject('Msxml2.XMLHTTP');
		} catch (e) {
			return new ActiveXObject('Microsoft.XMLHTTP');
		}
	}
}

function sendPost (req, url, params) {
	req.open('POST', url, true);
	req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	req.setRequestHeader('Content-length', params.length);
	req.setRequestHeader('Connection', 'close');
	req.send(params);
}

function encodeErrorXML (code, message) {
	return
		'<?xml version="1.0" ?>' +
		'<error>' +
		'<code>' + 
		code +
		'</code>' +
		'<message>' +
		message +
		'</message>' +
		'<detail>' +
		'</detail>' +
		'</error>';
}

function getErrorCode (xml) {
	if (xml.getElementsByTagName('error')[0].getElementsByTagName('code')[0].childNodes.length > 0)
		return parseInt(xml.getElementsByTagName('error')[0].getElementsByTagName('code')[0].childNodes[0].nodeValue, 10);
	else
		return '';
}

function getErrorMessage (xml) {
	if (xml.getElementsByTagName('error')[0].getElementsByTagName('message')[0].childNodes.length > 0)
		return xml.getElementsByTagName('error')[0].getElementsByTagName('message')[0].childNodes[0].nodeValue;
	else
		return '';
}

function getErrorDetail (xml) {
	if (xml.getElementsByTagName('error')[0].getElementsByTagName('detail')[0].childNodes.length > 0)
		return xml.getElementsByTagName('error')[0].getElementsByTagName('detail')[0].childNodes[0].nodeValue;
	else
		return '';
}

function getErrorString (xml) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	return zeroPad(code, 6) + ': ' + message;
}

function zeroPad (num, width) {
	var numPadded = num + '';
	while(numPadded.length < width)
		numPadded = "0" + numPadded;
	return numPadded;
}

function getBrowser () {
	var moz = (typeof document.implementation != 'undefined') && (typeof
			document.implementation.createDocument != 'undefined');
	var ie = (typeof window.ActiveXObject != 'undefined');
	if (moz)
		return 'moz';
	else if (ie)
		return 'ie';
	else
		return 'other';
}

function getXMLDocument (xml) {
	var xmlDoc;
	var brows = getBrowser();
	if (brows == 'moz') {
		parser = new DOMParser();
		xmlDoc = parser.parseFromString(xml, 'text/xml');
		//xmlDoc = document.implementation.createDocument('', '', null);
		//xmlDoc.onload = readXML;		
	} else if (brows == 'ie') {
		xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
		xmlDoc.async = false;
		while(xmlDoc.readyState != 4) {};
		xmlDoc.loadXML(xml);
	}
	return xmlDoc;
}
